const clubService = require('../service/club.service')
const userService = require('../service/user.service')
const {
	CLUB_IS_ALREADY_EXISTS,
	NAME_IS_NOT_EXISTS
} = require('../config/error')
const verifyClub = async (ctx, next) => {
	// 2.判断社团是否存在
	try {
		const { name } = ctx.request.body
		const clubs = await clubService.findClubByName(name)
		if (clubs.length) {
			ctx.app.emit('error', CLUB_IS_ALREADY_EXISTS, ctx)
			return
		}
	} catch (error) {
		throw error
	}

	// 执行下一步
	await next()
}

const verifyLeaderName = async (ctx, next) => {
	// 2.判断用户是否存在
	try {
		const { leaderName } = ctx.request.body
		console.log(leaderName)
		const users = await userService.findUserByName(leaderName)
		if (!users.length) {
			ctx.app.emit('error', NAME_IS_NOT_EXISTS, ctx)
			return
		}

		ctx.request.body.leader_id = users[0].id
	} catch (error) {
		throw error
	}

	// 执行下一步
	await next()
}
const verifyClubNameUnique = async (ctx, next) => {
	try {
		const { club_id } = ctx.params // 从URL中获取社团ID（如果是更新操作）
		const { name } = ctx.request.body // 从请求体中获取新的社团名字
		console.log(club_id, name)
		const existingClubs = await clubService.queryClubNameUnique(name, club_id)
		if (existingClubs.length > 0) {
			// 如果找到其他社团使用了这个名字
			ctx.app.emit('error', CLUB_IS_ALREADY_EXISTS, ctx)
			return
		}

		// 如果名字是唯一的，继续执行后续中间件
		await next()
	} catch (error) {}
}
module.exports = {
	verifyClub,
	verifyLeaderName,
	verifyClubNameUnique
}
